<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header">
        <span>{{ { add: '试题录入', edit: '试题编辑' }[mode] }}</span>
      </div>
      <el-form label-width="100px" :model="form" :rules="rules" ref="form">
        <el-form-item label="学科:" prop="subjectID">
          <template>
            <el-select
              v-model="form.subjectID"
              placeholder="请选择"
              @change="changeSubject()"
            >
              <el-option
                v-for="item in simple"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="目录:" prop="catalogID">
          <template>
            <el-select v-model="form.catalogID" placeholder="请选择">
              <el-option
                v-for="item in catalog"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <template>
            <el-select v-model="form.enterpriseID" placeholder="请选择">
              <el-option
                v-for="item in enterprise"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="城市:" prop="province">
          <div class="city">
            <template>
              <el-select
                v-model="form.province"
                placeholder="请选择"
                @change="form.city = ''"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </template>

            <template>
              <el-select v-model="form.city" placeholder="请选择">
                <el-option
                  v-for="item in citysList"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </template>
          </div>
        </el-form-item>
        <el-form-item label="方向:" prop="direction">
          <template>
            <el-select v-model="form.direction" placeholder="请选择">
              <el-option
                v-for="item in direction"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="题型:" prop="questionType">
          <template>
            <el-radio-group
              v-model="form.questionType"
              @change="changeQuestionType"
            >
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <template>
            <el-radio-group v-model="form.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="题干:" style="height: 80%" prop="question">
          <!-- Two-way Data-Binding -->
          <quill-editor
            id="edit1"
            ref="myQuillEditor1"
            v-model="form.question"
            :options="editorOption1"
          />
          <el-upload
            accept="image/*"
            mutiple
            id="imageupload1"
            action="#"
            v-show="false"
            :before-upload="beforeUpload"
            :http-request="
              res => {
                return httpRequest(res, 'question')
              }
            "
          ></el-upload>
        </el-form-item>

        <el-form-item label="选项:" v-if="form.questionType !== '3'">
          <div
            class="option_item"
            v-for="item in form.options"
            :key="item.code"
          >
            <el-radio
              @change="changeRadio(item.code)"
              v-model="item.isRight"
              :label="1"
              v-if="form.questionType === '1'"
              >{{ item.code + '：' }}</el-radio
            >
            <el-checkbox
              :true-label="1"
              :false-label="0"
              v-model="item.isRight"
              v-else-if="form.questionType === '2'"
              >{{ item.code + '：' }}</el-checkbox
            >
            <el-input v-model="item.title" style="width: 250px"></el-input>
            <!--  <div class="image-upload">
              <el-upload
                action="#"
                list-type="picture-card"
                :limit="1"
                :auto-upload="false"
                :file-list="fileList"
                :on-preview="preview"
                :on-remove="handleRemove"
                :on-change="changeFile"
                :class="{ disabled: fileComputed }"
              >
                <i class="upload-text">上传图片</i>
                <i class="el-icon-circle-close" @click="handleRemove"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </div> -->
            <div class="image-upload">
              <el-upload
                accept="image/*"
                :disabled="Boolean(item.img)"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :http-request="
                  res => {
                    return httpRequest(res, item.code)
                  }
                "
              >
                <i class="upload-text" v-show="!item.img">上传图片</i>
                <i
                  class="el-icon-zoom-in"
                  v-show="item.img"
                  @click.stop="showBigImage(item.img)"
                ></i>
                <img
                  v-if="item.img"
                  :src="'http://' + item.img"
                  class="avatar"
                  style="width: 98px; height: 58px"
                />

                <i
                  class="el-icon-circle-close"
                  @click.stop="handleRemoveImg(item.code)"
                ></i>
              </el-upload>
              <el-dialog :visible.sync="isShow" title="图片预览">
                <div style="text-align: center">
                  <img
                    class="img"
                    :src="'http://' + BigImage"
                    alt="图片加载失败"
                    style="width: 50%; height: 50%"
                  />
                </div>
              </el-dialog>

              <!-- 预览图片 -->

              <!-- 进度条 -->
              <transition name="progress">
                <el-progress
                  color="skyblue"
                  v-if="progress[item.code].showProgress"
                  :percentage="progress[item.code].percentage"
                />
              </transition>
            </div>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              style="margin-left: 10px"
              @click="delOptions(item.code)"
            ></el-button>
          </div>

          <el-button
            type="danger"
            :disabled="form.questionType !== '2'"
            @click="addOptionItem"
            >+ 增加选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频:" prop="videoURL">
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" style="height: 80%" prop="answer">
          <!-- 富文本编辑器 -->
          <quill-editor
            id="edit2"
            ref="myQuillEditor2"
            v-model="form.answer"
            :options="editorOption2"
          />
          <el-upload
            accept="image/*"
            mutiple
            id="imageupload2"
            action="#"
            v-show="false"
            :before-upload="beforeUpload"
            :http-request="
              res => {
                return httpRequest(res, 'answer')
              }
            "
          ></el-upload>
        </el-form-item>
        <el-form-item label="题目备注" prop="remarks">
          <el-input
            class="textarea"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.remarks"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="试题标签:" prop="tags">
          <el-select
            v-model="tagsArr"
            allow-create
            placeholder="请选择试题标签"
            filterable
            multiple
            @visible-change="simpleTags"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { add, update, detail } from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/subjects'
import { simple as simpleDirectorys } from '@/api/hmmm/directorys'
import { list } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { simple as simpleTags } from '@/api/hmmm/tags'
// 上传图片
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDXu0pOghSyEDvMbZHrHSN2SdYFhwve7LK',
  SecretKey: 'mDWbQzIL7evwhCQDn7E7mBKCpCMI0SeZ'
})
export default {
  created () {
    this.getSimple()
    this.getEnterpriseList()
    this.simpleTags()
    if (this.mode === 'edit') {
      this.getDetail(this.id)
    }
  },
  computed: {
    citysList () {
      return citys(this.form.province)
    },

    mode () {
      return this.$route.query.id ? 'edit' : 'add'
    },
    id () {
      return this.$route.query.id | ''
    },
    // 设定一个计算属性 判断是否已经上传完了一张
    fileComputed () {
      return this.fileList.length === 1
    }
  },

  data () {
    return {
      // 图片上传相关
      // 图片预览
      BigImage: '',
      progress: {
        A: { percentage: 0, showProgress: false },
        B: { percentage: 0, showProgress: false },
        C: { percentage: 0, showProgress: false },
        D: { percentage: 0, showProgress: false },
        E: { percentage: 0, showProgress: false },
        F: { percentage: 0, showProgress: false },
        G: { percentage: 0, showProgress: false },
        H: { percentage: 0, showProgress: false },
        I: { percentage: 0, showProgress: false },
        J: { percentage: 0, showProgress: false },
        K: { percentage: 0, showProgress: false },
        L: { percentage: 0, showProgress: false },
        M: { percentage: 0, showProgress: false },
        N: { percentage: 0, showProgress: false },
        O: { percentage: 0, showProgress: false }
      },
      isShow: false,
      // 表单验证
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          {
            required: true,
            message:
              '请选择目录，如果该列表为空，请确认您选择的学科下有目录，添加后重试',
            trigger: 'change'
          }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (this.form.city === '') callback(new Error('请选择城市'))
              else {
                callback()
              }
            }
          }
        ],
        tags: [
          {
            validator: (rule, value, callback) => {
              if (this.tagsArr.length === 0) callback(new Error('请设置标签'))
              else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        videoURL: [
          { required: true, message: '请填写视频地址', trigger: 'change' }
        ],
        remarks: [
          { required: true, message: '请填写备注信息', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入问题', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.length >= 1000) {
                callback(new Error('内容过长，请删减后重试'))
              } else {
                callback()
              }
            }
          }
        ],

        answer: [
          { required: true, message: '请输入答案', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.length >= 1000) {
                callback(new Error('内容太长，请删减后重试'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      // 默认选项
      options: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: 1
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: 0
        }
      ],
      // 富文本编辑器配置项
      editorOption1: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              ['blockquote', 'code-block'], // 引用  代码块
              ['image', 'link'] // 链接、图片、视频
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  document
                    .querySelector('#imageupload1 .el-upload__input')
                    .click()
                }
              }
            }
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        } // 工具菜单栏配置
      },
      // 富文本编辑器配置项
      editorOption2: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              ['blockquote', 'code-block'], // 引用  代码块
              ['image', 'link'] // 链接、图片、视频
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  document
                    .querySelector('#imageupload2 .el-upload__input')
                    .click()
                }
              }
            }
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        } // 工具菜单栏配置
      },

      placeholder: '在此输入内容',
      readyOnly: false, // 是否只读
      theme: 'snow', // 主题 snow/bubble
      syntax: true, // 语法检查
      // 表单
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        videoURL: '',
        answer: '',
        remarks: '',
        tags: '',
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 1
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: 0
          }
        ]
      },

      // 列表
      simple: [],
      catalog: [],
      direction,
      provinces: provinces(),
      citys: [],
      enterprise: [],
      tagsList: [],
      tagsArr: []
    }
  },
  watch: {
    id: function (val) {
      if (val) {
        this.getDetail(val)
      } else {
        this.$refs.form.resetFields()
      }
    }
  },
  methods: {
    // 获取options索引
    getIndex (code) {
      const index = this.form.options.findIndex(item => {
        return item.code === code
      })
      return index
    },
    // 图片
    /*     handleUploadSuccess () {
      console.log('上传成功')

      // handleUploadSuccess (res, file, code) {
      //   console.log('上传成功')
      //   console.log('res:' + res)
      //   console.log('file:' + file)
      //   console.log('code:' + code)
      //   console.log(
      //     this.form.options.findIndex((item) => {
      //       return item.code === code
      //     })
      //   )

      // this.imageUrl = URL.createObjectURL(file.raw)
    }, */
    beforeUpload (file) {
      // console.log(file)
      // 上传前，限制 文件大小与类型
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/gif'
      const limit2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只支持png、jpg、gif格式的图片')
      }
      if (!limit2M) {
        this.$message.error('请上传2MB内的图片')
      }
      return isImage && limit2M
    },
    httpRequest (res, code) {
      if (code === 'question' || code === 'answer') {
        cos.putObject(
          {
            Bucket: 'gogomusic-1251140474' /* 存储桶: */,
            Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
            Key: res.file.uid + '' /* 必须是字符串 */,
            StorageClass: 'STANDARD', // 固定值
            Body: res.file // 上传文件对象
          },
          (err, data) => {
            if (data) {
              var quill

              // 获取文本编辑器
              switch (code) {
                case 'question':
                  quill = this.$refs.myQuillEditor1.quill
                  break
                case 'answer':
                  quill = this.$refs.myQuillEditor2.quill
                  break
              }

              // 获取光标位置
              const pos = quill.getSelection().index
              // 插入图片到光标位置
              quill.insertEmbed(pos, 'image', 'http://' + data.Location)
            } else {
              this.$message.error(
                `图片插入失败
    ${err}
`
              )
            }
            //   this.imageUrl = 'http://' + data.Location
            // this.$emit('input', 'http://' + data.Location)
          }
        )
      } else {
        // 显示上传进度
        this.progress[code].showProgress = true
        this.progress[code].percentage = 0
        cos.putObject(
          {
            Bucket: 'gogomusic-1251140474' /* 存储桶: */,
            Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
            Key: res.file.uid + '' /* 必须是字符串 */,
            StorageClass: 'STANDARD', // 固定值
            Body: res.file, // 上传文件对象
            onProgress: progressData => {
              // 上传进度
              this.progress[code].percentage = progressData.percent * 100
              // progressData.percent=1上传完成
              if (progressData.percent === 1) {
                setTimeout(() => {
                  this.progress[code].showProgress = false
                }, 1000)
              }
              setTimeout(() => {
                if (progressData.percent < 0.5 && progressData.percent !== 0) {
                  this.$message.error('网速较慢，请等待...')
                }
              }, 3000)
              // console.log(JSON.stringify(progressData))
            }
          },
          (err, data) => {
            // 上传成功或者失败的回调

            // console.log(err || data)
            // console.log('this', this)
            // console.log(data.Location)
            if (data) {
              this.form.options[this.getIndex(code)].img = data.Location
            } else {
              this.$message.error(
                `上传失败
    ${err}
`
              )
              this.progress[code].showProgress = false
            }

            //   this.imageUrl = 'http://' + data.Location
            // this.$emit('input', 'http://' + data.Location)
          }
        )
      }
    },

    showBigImage (img) {
      // 图片点击处理
      this.isShow = true
      this.BigImage = img
    },
    handleRemoveImg (code) {
      this.form.options[this.getIndex(code)].img = ''
    },
    // 添加多选项
    addOptionItem () {
      if (this.form.options.length <= 10) {
        this.form.options.push({
          code: String.fromCharCode(
            this.form.options[this.form.options.length - 1].code.charCodeAt() +
              1
          ),
          title: '',
          img: '',
          isRight: 0
        })
      } else {
        this.$message.error('最多添加10个选项')
      }
    },
    // 删除选项
    delOptions (code) {
      if (this.form.options.length === 2) {
        this.$message.error('请至少保留两项！')
      } else {
        this.form.options.splice(this.getIndex(code), 1)
        // 重新排序
        let optionCode = 64
        this.form.options.forEach(item => {
          item.code = String.fromCharCode((optionCode += 1))
        })
      }
    },
    // 获取学科列表
    async getSimple () {
      const { data } = await simple()
      this.simple = data
    },
    // 获取二级目录
    async getSimpleDirectorys () {
      const { data } = await simpleDirectorys({
        subjectID: this.form.subjectID
      })
      this.catalog = data
    },
    // 更改学科
    changeSubject () {
      this.getSimpleDirectorys()
      this.form.catalogID = ''
    },
    // 获取企业列表
    async getEnterpriseList () {
      const { data } = await list({ pagesize: 10000 })
      this.enterprise = data.items
    }, // 改变题型时
    changeQuestionType () {
      this.form.options.forEach(item => {
        item.isRight = false
      })
    },
    // 获取标签列表
    async simpleTags () {
      const { data } = await simpleTags({ subjectID: this.form.subjectID })
      this.tagsList = data
    },

    // 提交表单
    submit () {
      if (this.form.questionType === '3') {
        this.form.options = [...this.options]
      }
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            await add({ ...this.form, tags: this.tagsArr.join(',') })
          } else if (this.mode === 'edit') {
            const data = {
              ...this.form,
              id: this.id,
              tags: this.tagsArr.join(',')
            }

            await update(data)
          }
          this.$message.success('提交成功！')
          this.tags = []
          this.$refs.form.resetFields()
          this.form = {
            subjectID: '',
            catalogID: '',
            enterpriseID: '',
            province: '',
            city: '',
            direction: '',
            questionType: '1',
            difficulty: '1',
            question: '',
            videoURL: '',
            answer: '',
            remarks: '',
            tags: '',
            options: [
              {
                code: 'A',
                title: '',
                img: '',
                isRight: 1
              },
              {
                code: 'B',
                title: '',
                img: '',
                isRight: 0
              },
              {
                code: 'C',
                title: '',
                img: '',
                isRight: 0
              },
              {
                code: 'D',
                title: '',
                img: '',
                isRight: 0
              }
            ]
          }
          this.$router.push('/questions/list')
        } else {
          this.$message.error('请检查你的输入，修改后重试')
        }
      })
    }, // 获取题目详情
    async getDetail (id) {
      const res = await detail({ id })
      this.form = res.data
      if (
        this.form.options.length === 0 ||
        !(this.form.options instanceof Array)
      ) {
        this.form.options = [...this.options]
        this.form.options[0].isRight = false
      }

      // 选项排序
      this.form.options.sort(function (a, b) {
        return a.code.charCodeAt() - b.code.charCodeAt()
      })
      this.tagsArr = res.data.tags.split(',')
    },
    // 单选框互斥
    changeRadio (code) {
      this.form.options.forEach(item => {
        if (item.code !== code) {
          item.isRight = 0
        } else {
          item.isRight = 1
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.box-card {
  margin: 20px 25px 0;
  .el-form {
    .el-form-item {
      ::v-deep .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      ::v-deep .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
      .uploadImg {
        position: relative;
        width: 178px;
        &:hover {
          .close {
            display: block;
          }
        }
        .close {
          display: none;
          position: absolute;
          top: 5px;
          right: 10px;
          cursor: pointer;
        }
      }
      .el-progress--line {
        transform: translateY(-300%);
        margin-left: 10px;
      }
      .progress-enter-active,
      .progress-leave-active {
        transition: all 0.5s;
      }
      .progress-enter,
      .progress-leave-to {
        opacity: 0;
      }
      .el-select,
      .textarea,
      .city {
        width: 400px;
        .el-select {
          width: 50%;
        }
        &:nth-child(2) {
          padding-left: 5px;
        }
      }
      .disabled {
        display: none;
      }
      .el-form-item__content {
        .quill-editor {
          height: 250px;
          width: 100%;
          overflow: hidden;
          padding-bottom: 55px;
        }
      }

      .option_item {
        display: flex;
        width: 500px;
        align-items: center;
        padding: 10px;
        .el-input {
          width: 300px;
          margin-right: 10px;
        }
        .el-radio,
        .el-checkbox {
          margin-right: 5px;
        }
      }
      .image-upload {
        position: relative;
        height: 60px;
        .el-icon-zoom-in {
          position: absolute;
          bottom: 0;
          right: 0;
        }
        ::v-deep .el-upload {
          overflow: visible !important;
        }
        ::v-deep .el-upload-list__item {
          width: 100px;
          height: 60px;
          & > div {
            height: 100%;
          }
        }
        ::v-deep .el-upload {
          position: relative;
          width: 100px;
          height: 60px;
          line-height: 60px;

          .upload-text {
            font-size: 12px;
            font-style: normal;
            color: #000;
            line-height: 60px;
          }

          .el-icon-circle-close {
            font-size: 18px;
            position: absolute;
            right: -9px;
            top: -9px;
          }
        }
      }
    }
  }
}
</style>
